package com.basis.handler;

import java.util.Date;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Query;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import com.mes.data.EmesMessageUserLog;

public class MessageSetReadHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject result = new JSONObject();
		try {
			OBContext.setAdminMode();
			JSONObject jsonData = new JSONObject(data);
			String messageId = jsonData.getString("messageId");
			
			String hql = "from Emes_Message_User_Log l " +
					"where l.sendMode = 'WINDOW'" +
					"  and nvl(l.status, 'CREATE') = 'CREATE' " +
					"  and l.emesMessage.id = ?" +
					"  and l.user.id = ?";
			
			Query query = OBDal.getInstance().getSession().createQuery(hql);
			query.setString(0, messageId);
			query.setString(1, SessionInfo.getUserId());
			EmesMessageUserLog log = (EmesMessageUserLog)query.uniqueResult();
			if (log != null) {
				log.setStatus(true);
				log.setLogTime(new Date());
				OBDal.getInstance().save(log);
			}

			result.put("success", true);
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			e.printStackTrace();
			OBDal.getInstance().rollbackAndClose();
			logger.error("设置消息提醒内容为已读异常：" + e.getMessage(), e);
			try {
				result.put("success", false);
				result.put("msg", "设置消息提醒内容为已读异常");
			} catch (Exception e1) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return result;
	}
}
